using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DrawerMenu.Services;
using DrawerMenu.ViewModels;

namespace DrawerMenu;

public partial class MainViewModel : ObservableObject
{
    [ObservableProperty]
    private bool _isDrawerOpen;

    [ObservableProperty]
    private double _drawerOffset = -280;

    public INavigationService NavigationService { get; }

    public MainViewModel(INavigationService navigationService)
    {
        NavigationService = navigationService;
    }

    [RelayCommand]
    private void ToggleDrawer()
    {
        if (IsDrawerOpen)
        {
            CloseDrawer();
        }
        else
        {
            OpenDrawer();
        }
    }

    private void OpenDrawer()
    {
        IsDrawerOpen = true;
        AnimateDrawer(0);
    }

    [RelayCommand]
    public void CloseDrawer()
    {
        IsDrawerOpen = false;
        AnimateDrawer(-280);
    }

    private void AnimateDrawer(double targetOffset)
    {
        var from = DrawerOffset;
        var startTime = DateTime.Now;

        var timer = new System.Windows.Threading.DispatcherTimer
        {
            Interval = TimeSpan.FromMilliseconds(16)
        };

        timer.Tick += (s, e) =>
        {
            var elapsed = (DateTime.Now - startTime).TotalMilliseconds;
            var progress = Math.Min(elapsed / 300.0, 1.0);

            var easeProgress = 1 - Math.Pow(1 - progress, 2);
            DrawerOffset = from + (targetOffset - from) * easeProgress;

            if (progress >= 1.0)
            {
                timer.Stop();
                DrawerOffset = targetOffset;
            }
        };

        timer.Start();
    }

    [RelayCommand]
    private void Navigate(string? page)
    {
        if (string.IsNullOrEmpty(page))
            return;

        switch (page)
        {
            case "Home":
                NavigationService.NavigateTo<HomeViewModel>();
                break;
            case "Profile":
                NavigationService.NavigateTo<ProfileViewModel>();
                break;
            case "Settings":
                NavigationService.NavigateTo<SettingsViewModel>();
                break;
            case "About":
                NavigationService.NavigateTo<AboutViewModel>();
                break;
        }

        CloseDrawer();
    }
}
